package com.tledu.web_01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/stu/register", loadOnStartup = 1)
public class StuRegisterServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
        // 向servletContext 域中放置了一个数据
        this.getServletContext().setAttribute("list", new ArrayList<String>());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println("  <form method=\"post\">\n" +
                "      <input name=\"name\" />\n" +
                "      <button type=\"submit\">提交</button>\n" +
                "  </form>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        System.out.println(name);
        // 放到servletContext
//        req.getServletContext();
        //每次注册向这个域中添加一个数据
        List<String> list = (List<String>) this.getServletContext().getAttribute("list");
        list.add(name);
        // 跳转到管理界面
        resp.sendRedirect(req.getContextPath() + "/stu/manager");
    }
}
